<script setup>
import {computed, ref} from "vue";
import {http} from "@/api";
import VChart from "vue-echarts";
import { ElMessage as Message } from "element-plus";
import RelTimeLine from "@/views/photovoltaic-storage-coordination/real-time-line.vue";
import DayLine from "@/views/photovoltaic-storage-coordination/day-line.vue";
const baseDetail = ref({
  // 场级告警
  field_level_alarm: '0',
  // 场级AGC允许
  field_agc_allow: '0',
  // 控制方式（调度/手动）
  control_mode: '0',
  // 实时电价 (元)
  real_time_price: '',
  // 实时电网指令 (MW)
  real_time_grid_command: '',
  // 电网指令与光储调度值差限 (MW)
  grid_command_difference_limit: '',
  // 实时光伏出力功率 (MW)
  real_time_photovoltaic_power: '',
  // 实时储能出力功率 (MW)
  real_time_storage_power: '',
  // 实时光储调度指令 (MW)
  real_time_photovoltaic_storage_command: '',
  // 电网
  grid_command: '',
  // 光出调度指令
  photovoltaic_dispatch_command: '',
})
const getDetail = () => {
  http.pvCoordination.list().then(res => {
    const obj = {}
    res.data.forEach(item => {
      obj[item.code] = item.value
    })
    for (const formData1Key in baseDetail.value) {
      if (baseDetail.value.hasOwnProperty(formData1Key)) {
        baseDetail.value[formData1Key] = obj[formData1Key]
      }
    }
    if (!baseDetail.value.grid_command_difference_limit) {
      baseDetail.value.grid_command_difference_limit = 0
    }
    getData()
  })
}
getDetail()

const option1 = ref({
  backgroundColor: "#FFF",
  grid: {
    top: "50",
    bottom: "5",
    left: "0",
    right: "0",
    containLabel: true
  },
  tooltip: {
    trigger: "axis",
    label: {
      show: true,
    },
  },
  xAxis: {
    boundaryGap: true, //默认，坐标轴留白策略
    axisLine: {
      show: true,
      lineStyle: {
        color: "rgba(33,148,246,0.8)",
      },
    },
    splitLine: {
      show: false,
    },
    axisTick: {
      show: true,
      alignWithLabel: true,
    },
    data: [

    ],
  },
  yAxis: [
    {
      splitLine: {
        show: false,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(33,148,246,0.8)",
        },
      },
      axisTick: {
        show: true,
      },
      splitArea: {
        show: false,
        areaStyle: {
          color: "rgb(245,250,254)",
        },
      },
    },
    {
      splitLine: {
        show: false,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(33,148,246,0.8)",
        },
      },
      axisTick: {
        show: true,
      },
      splitArea: {
        show: false,
        areaStyle: {
          color: "rgb(245,250,254)",
        },
      },
    }
  ],
  legend: {
    show: true,
    right: "center",
    top: "10",
    textStyle: {
      color: "rgb(33,148,246)",
    },
    data: ["电网指令", "光储调度指令"],
  },
  series: [
    {
      name: '电网指令',
      type: "line",
      symbol: "circle",
      symbolSize: 2,
      smooth: false,
      yAxisIndex: 0,

      lineStyle: {
        color: "rgb(33,148,246)",
      },
      itemStyle: {
        color: "rgb(33,148,246)",
        borderWidth: 1,
      },
      data: [

      ],
    },
    {
      name: '光储调度指令',
      type: "line",
      symbol: "circle",
      symbolSize: 2,
      smooth: false,
      yAxisIndex: 1,
      lineStyle: {
        color: "rgb(236,217,28)",
      },
      itemStyle: {
        color: "rgb(236,217,28)",
        borderWidth: 1,
      },
      data: [

      ],
    },
  ],
})
const option2 = ref({
  backgroundColor: "#FFF",
  grid: {
    top: "50",
    bottom: "5",
    left: "0",
    right: "0",
    containLabel: true
  },
  tooltip: {
    trigger: "axis",
    label: {
      show: true,
    },
  },
  xAxis: {
    boundaryGap: true, //默认，坐标轴留白策略
    axisLine: {
      show: true,
      lineStyle: {
        color: "rgba(33,148,246,0.8)",
      },
    },
    splitLine: {
      show: false,
    },
    axisTick: {
      show: true,
      alignWithLabel: true,
    },
    data: [

    ],
  },
  yAxis: [
    {
      splitLine: {
        show: false,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(33,148,246,0.8)",
        },
      },
      axisTick: {
        show: true,
      },
      splitArea: {
        show: false,
        areaStyle: {
          color: "rgb(245,250,254)",
        },
      },
    },
    {
      splitLine: {
        show: false,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(33,148,246,0.8)",
        },
      },
      axisTick: {
        show: true,
      },
      splitArea: {
        show: false,
        areaStyle: {
          color: "rgb(245,250,254)",
        },
      },
    }
  ],
  legend: {
    show: true,
    right: "center",
    top: "10",
    textStyle: {
      color: "rgb(33,148,246)",
    },
    data: ["电网指令", "光储调度指令"],
  },
  series: [
    {
      name: '电网指令',
      type: "line",
      symbol: "circle",
      symbolSize: 2,
      smooth: false,
      yAxisIndex: 0,

      lineStyle: {
        color: "rgb(33,148,246)",
      },
      itemStyle: {
        color: "rgb(33,148,246)",
        borderWidth: 1,
      },
      data: [

      ],
    },
    {
      name: '光储调度指令',
      type: "line",
      symbol: "circle",
      symbolSize: 2,
      smooth: false,
      yAxisIndex: 1,
      lineStyle: {
        color: "rgb(236,217,28)",
      },
      itemStyle: {
        color: "rgb(236,217,28)",
        borderWidth: 1,
      },
      data: [

      ],
    },
  ],
})
const relTimeData = ref([])
// 当前时间
const currentRelTimeData = computed(() => {
  if (relTimeData.value.length > 1) {
    return relTimeData.value[relTimeData.value.length - 2]
  }
  return {
    grid_command: 0,
    photovoltaic_dispatch_command: 0
  }
})
const forcastDataItem = ref({
  id: undefined,
  grid_command: 0,
  photovoltaic_dispatch_command: 0
})
// 日前预测
const forcastData = computed(() => {
  if (relTimeData.value.length > 1) {
    forcastDataItem.value = relTimeData.value[relTimeData.value.length - 1]
    return forcastDataItem.value
  }
  return {
    grid_command: 0,
    photovoltaic_dispatch_command: 0
  }
})
const getData = () => {
  http.pvCoordinationRecord.list({
    type: 'realtime'
  }).then(res => {
    const data = res.data
    relTimeData.value = data
    const xData = data.map(item => item.name)
    const yData1 = data.map(item => item.grid_command)
    const yData2 = data.map(item => item.photovoltaic_dispatch_command)
    option1.value.xAxis.data = xData
    option1.value.series[0].data = yData1
    option1.value.series[1].data = yData2
    diffLimit()
  })
  http.pvCoordinationRecord.list({
    type: 'day'
  }).then(res => {
    const data = res.data
    const xData = data.map(item => item.name)
    const yData1 = data.map(item => item.grid_command)
    const yData2 = data.map(item => item.photovoltaic_dispatch_command)
    option2.value.xAxis.data = xData
    option2.value.series[0].data = yData1
    option2.value.series[1].data = yData2
  })
}
const differenceValue = ref(0)
const diffLimit = () => {
  if (relTimeData.value.length > 1) {
    const lastItem = relTimeData.value[relTimeData.value.length - 1]
    const lastGridCommand = lastItem.grid_command || 0
    const lastPhotovoltaicDispatchCommand = lastItem.photovoltaic_dispatch_command || 0
    // 绝对值
    const difference = Math.abs(lastGridCommand - lastPhotovoltaicDispatchCommand)
    differenceValue.value = difference
    if (difference > baseDetail.value.grid_command_difference_limit) {
      if(baseDetail.value.control_mode === '0') {
        Message.warning('电网指令与光储调度值差限超限')
        updateCode('control_mode', '1')
        baseDetail.value.control_mode = '1'
      }
    }
  }
}
const updateCode = (code, value) => {
  http.pvCoordination.update({
    [code]: value
  }).then(res => {
    Message.success('操作成功')
    if (code === 'grid_command_difference_limit') {
      diffLimit()
    }
  })
}
// 手动控制保存
const saveCommandValue = () => {
  http.pvCoordinationRecord.update(forcastDataItem.value).then(res => {
    Message.success('保存成功')
    getData()
  })
}
</script>

<template>
  <div class="data-container">
    <el-card shadow="never" style="margin-bottom: 20px">
      <template #header>
        <div class="card-header">
          <span>基本信息</span>
        </div>
      </template>
      <el-form label-suffix="：">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="场级告警">
              <el-button :type="{ 0: 'danger', 1: 'success'}[baseDetail.field_level_alarm]" circle size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实时电价（元）">
              {{ baseDetail.real_time_price }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实时光伏出力功率（MW）">
              {{ baseDetail.real_time_photovoltaic_power }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="场级AGC允许">
              <el-radio-group v-model="baseDetail.field_agc_allow" @change="(val) => updateCode('field_agc_allow', val)">
                <el-radio label="1">允许</el-radio>
                <el-radio label="0">退出</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实时电网指令（MW）">
              {{ baseDetail.real_time_grid_command }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实时储能出力功率（MW）">
              {{ baseDetail.real_time_storage_power }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="控制方式（调度/手动）">
              <el-radio-group v-model="baseDetail.control_mode" @change="(val) => updateCode('control_mode', val)">
                <el-radio label="0">调度控制</el-radio>
                <el-radio label="1">手动控制</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电网指令与光储调度值差限（MW）">
              <el-input v-model="baseDetail.grid_command_difference_limit" @blur="val => updateCode('grid_command_difference_limit', baseDetail.grid_command_difference_limit)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实时光储调度指令（MW）">
              {{ baseDetail.real_time_photovoltaic_storage_command }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-row :gutter="10">
      <el-col :span="16">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>实时光储调度指令（15min）单位：MW</span>
            </div>
          </template>
          <v-chart ref="echartsRef1" class="chart" style="height: 250px" :option="option1" autoresize />

        </el-card>
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>日前光储调度指令（24h）单位：MW</span>
            </div>
          </template>
          <v-chart ref="echartsRef2" class="chart" style="height: 250px" :option="option2" autoresize />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never" style="height: 100%">
          <template #header>
            <div class="card-header">
              <span>电网指令与光储调度值差值（MW）：{{ differenceValue }}</span>
            </div>
          </template>
          <div style="display: flex;justify-content: space-between;align-items: center">
            <div>
              <span>超限告警：</span>
              <el-button :type="differenceValue > baseDetail.grid_command_difference_limit ? 'danger': 'success'" circle size="small"/>
            </div>
            <div style="font-size: 14px">
              <p>可调上限（MW)：210</p>
              <p>可调下限（MW)：150</p>
            </div>
          </div>
          <div style="margin: 50px 0;display: flex;justify-content: center;align-items: center">
            <el-progress status="success" type="circle" :percentage="currentRelTimeData.photovoltaic_dispatch_command / 210 * 100">
              <template #default="{ percentage }">
                <p class="percentage-value">{{ currentRelTimeData.photovoltaic_dispatch_command }}</p>
                <p class="percentage-label" style="font-size: 12px;margin-top: 10px">当前光储出力功率</p>
              </template>
            </el-progress>
            <div style="width: 50px"></div>
            <el-progress status="success" type="circle" :percentage="forcastData.photovoltaic_dispatch_command / 210 * 100">
              <template #default="{ percentage }">
                <p class="percentage-value">{{ forcastData.photovoltaic_dispatch_command }}</p>
                <p class="percentage-label" style="font-size: 12px;margin-top: 10px">实时光储调度指令</p>
              </template>
            </el-progress>
          </div>
          <div style="display:flex;align-items: center;justify-content: center;">
            <el-input-number :max="210" :min="150" v-model="forcastDataItem.photovoltaic_dispatch_command"></el-input-number>
          </div>
          <div style="display:flex;align-items: center;justify-content: center;">
            <el-button :disabled="baseDetail.control_mode !== '1'" @click="saveCommandValue" style="width: 160px;margin-top: 20px;" type="primary">保存</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-tabs type="border-card">
      <el-tab-pane label="实时">
        <RelTimeLine disabled/>
      </el-tab-pane>
      <el-tab-pane label="日前">
        <DayLine disabled/>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">

</style>